import os
import random
import time
import sys
from datetime import datetime
import ctypes
import atexit


class SafeGarbledGenerator:
    def __init__(self):
        # 限定在GB2312可编码范围（0x4E00-0x9FA5）
        self.char_range = (0x4E00, 0x9FA5)
        self.encoding_pairs = [
            ('gbk', 'big5'),
            ('gb18030', 'shift_jis'),
            ('gbk', 'iso-8859-1')
        ]
        self.cache = [self._safe_garbled() for _ in range(20)]

    def _safe_garbled(self):
        # 生成保证可编码的原始字符
        original = ''.join(chr(random.randint(*self.char_range)) for _ in range(50))

        for _ in range(3):  # 重试机制
            try:
                src, dst = random.choice(self.encoding_pairs)
                return original.encode(src, errors='replace').decode(dst, errors='replace')
            except UnicodeError:
                continue
        return original.encode('gbk', errors='ignore').decode('iso-8859-1', errors='replace')


class PowerManager:
    def __init__(self):
        if os.name == 'nt':
            self.kernel32 = ctypes.windll.kernel32
            self._set_state(True)
            atexit.register(self.cleanup)

    def _set_state(self, enable):
        state = 0x80000002 if enable else 0x80000000
        self.kernel32.SetThreadExecutionState(state)

    def cleanup(self):
        self._set_state(False)


def main():
    pm = PowerManager()
    generator = SafeGarbledGenerator()

    try:
        while True:
            ts = datetime.now().strftime("%m-%d %H:%M:%S")
            print(f"[{ts}] {generator._safe_garbled()}")
            sys.stdout.flush()
            time.sleep(0.08)
    except Exception as e:
        pm.cleanup()
        sys.exit(1)


if __name__ == "__main__":
    main()
